//
//  SocketAckEmitter.swift
//  QHSocketIODemo
//
//  Created by chen on 2017/5/16.
//  Copyright © 2017年 chen. All rights reserved.
//

import Foundation

public final class SocketAckEmitter: NSObject {
    let socket: SocketIOClient
    let ackNum: Int
    
    public var expected: Bool {
        return ackNum != -1
    }
    
    init(socket: SocketIOClient, ackNum: Int) {
        self.socket = socket
        self.ackNum = ackNum
    }
    
    public func with(_ items: SocketData...) {
        guard ackNum != -1 else { return }
        
        socket.emitAck(ackNum, with: items)
    }
    
    public func with(_ items: [Any]) {
        guard ackNum != -1 else { return }
        
        socket.emitAck(ackNum, with: items)
    }
}

public final class OnAckCallback: NSObject {
    private let ackNumber: Int
    private let items: [Any]
    private weak var socket: SocketIOClient?
    
    init(ackNumber: Int, items: [Any], socket: SocketIOClient) {
        self.ackNumber = ackNumber
        self.items = items
        self.socket = socket
    }
    
    deinit {
        
    }
    
    public func timingOut(after seconds: Int, callback: @escaping AckCallback) {
        guard let socket = self.socket else { return }
        
        socket.ackQueue.sync {
//            socket.ackHandlers.
        }
        
        socket._emit(items, ack: ackNumber)
        
        guard seconds != 0 else { return }
        
        let time = DispatchTime.now() + Double(UInt64(seconds) * NSEC_PER_SEC) / Double(NSEC_PER_SEC)
        
        socket.handleQueue.asyncAfter(deadline: time) { 
//            socket.ackHandlers.
        }
    }
}
